﻿
using SIG.Basic.Extensions;
using SIG.Data.Repositories.Case;
using SIG.Infrastructure.Cache;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Logging;
using SIG.Model.Blogs;
using SIG.Resources.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

namespace SIG.Service.Case
{
    public class PostService : EntityService<Post>, IPostService
    {

        private readonly IPostRepository _postRepository;
        private readonly ILoggingService _loggingService;
        private readonly ICacheService _cacheService;

        public PostService(IPostRepository postRepository, ILoggingService loggingService, ICacheService cacheService)
            : base(postRepository, cacheService, loggingService)
        {

            _postRepository = postRepository;
            _loggingService = loggingService;
            _cacheService = cacheService;
        }

        public async Task<IList<Post>> GetActiveElementsAync(CancellationToken cancellationToken = default(CancellationToken))
        {
            //get list
            var key = $"{EntityNames.Post}_List_Active";

            IList<Post> postlist;
            if (SettingsManager.Blog.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    postlist = (IList<Post>)_cacheService.Get(key);

                }
                else
                {
                    var post = await _postRepository.GetFilteredElementsAsync(m => m.Active, cancellationToken, g => g.PostCategory);
                    postlist = post.ToList();
                    _cacheService.Set(key, postlist, SettingsManager.Blog.CacheDuration);
                }
            }
            else
            {
                var posts = await _postRepository.GetFilteredElementsAsync(m => m.Active, cancellationToken, g => g.PostCategory);
                postlist = posts.ToList();
            }

            return postlist;

        }



        public Post GetPostDetail(int id)
        {
            return _postRepository.GetFirstOrDefault(m => m.Id == id, m => m.PostCategory);
        }

        public List<Post> GetPagedActiveElements(int pageIndex, int pageSize, string keyword, int? categoryId, out int totalCount)
        {

            //get list count
            var keyCount = $"{EntityNames.Post}_ListCount_Active_{keyword}_{categoryId}";

            var totalIQuery = _postRepository.GetAllElements().Where(g => g.Active);
            if (!string.IsNullOrEmpty(keyword))
                totalIQuery = totalIQuery.Where(g => g.Title.Contains(keyword));
            if (categoryId > 0)
                totalIQuery = totalIQuery.Where(g => g.CategoryId == categoryId);

            if (SettingsManager.Blog.EnableCaching)
            {
                if (_cacheService.IsSet(keyCount))
                {
                    totalCount = (int)_cacheService.Get(keyCount);
                }
                else
                {
                    totalCount = totalIQuery.Count();
                    _cacheService.Set(keyCount, totalCount, SettingsManager.Blog.CacheDuration);
                }
            }
            else
            {
                totalCount = totalIQuery.Count();
            }


            //get list
            var key = $"{EntityNames.Post}_List_Active_{pageIndex}_{pageSize}_{keyword}_{categoryId}";

            List<Post> post;
            Expression<Func<Post, bool>> filter = g => g.Active;
            Expression<Func<Post, bool>> filterByKeyword = g => g.Title.Contains(keyword);
            Expression<Func<Post, bool>> filterByCategory = g => g.CategoryId == categoryId;

            if (!string.IsNullOrEmpty(keyword))
                filter = filter.AndAlso(filterByKeyword);
            if (categoryId > 0)
                filter = filter.AndAlso(filterByCategory);


            if (SettingsManager.Blog.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    post = (List<Post>)_cacheService.Get(key);

                }
                else
                {
                    post = _postRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.PostCategory).ToList();
                    _cacheService.Set(key, post, SettingsManager.Blog.CacheDuration);
                }
            }
            else
            {
                post = _postRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.PostCategory).ToList();
            }

            return post;

        }





   



        public List<Post> GetPagedElements(int pageIndex, int pageSize, string keyword, int? categoryId, out int totalCount)
        {

            //get list count
            var keyCount = $"{EntityNames.Post}_ListCount_{keyword}_{categoryId}";

            var totalIQuery = _postRepository.GetAllElements();
            if (!string.IsNullOrEmpty(keyword))
                totalIQuery = totalIQuery.Where(g => g.Title.Contains(keyword));
            if (categoryId > 0)
                totalIQuery = totalIQuery.Where(g => g.CategoryId == categoryId);

            if (SettingsManager.Blog.EnableCaching)
            {
                if (_cacheService.IsSet(keyCount))
                {
                    totalCount = (int)_cacheService.Get(keyCount);
                }
                else
                {
                    totalCount = totalIQuery.Count();
                    _cacheService.Set(keyCount, totalCount, SettingsManager.Blog.CacheDuration);
                }
            }
            else
            {
                totalCount = totalIQuery.Count();
            }


            //get list
            var key = $"{EntityNames.Post}_List_{pageIndex}_{pageSize}_{keyword}_{categoryId}";

            List<Post> posts;
            Expression<Func<Post, bool>> filter = g => true;
            Expression<Func<Post, bool>> filterByKeyword = g => g.Title.Contains(keyword);
            Expression<Func<Post, bool>> filterByCategory = g => g.CategoryId == categoryId;

            if (!string.IsNullOrEmpty(keyword))
                filter = filter.AndAlso(filterByKeyword);
            if (categoryId > 0)
                filter = filter.AndAlso(filterByCategory);


            if (SettingsManager.Blog.EnableCaching)
            {
                if (_cacheService.IsSet(key))
                {
                    posts = (List<Post>)_cacheService.Get(key);
                }
                else
                {
                    posts = _postRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.PostCategory).ToList();
                    _cacheService.Set(key, posts, SettingsManager.Blog.CacheDuration);
                }
            }
            else
            {
                posts = _postRepository.GetPagedElements(pageIndex, pageSize, (c => c.CreatedDate), filter, false, g => g.PostCategory).ToList();
            }

            return posts;

        }



        public IEnumerable<Post> RecommendPosts(int count)
        {
            var key = $"{EntityNames.Post}s_Recommend";

            if (!SettingsManager.Blog.EnableCaching)
            {
                return _postRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active && p.Recommend, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Post>)_cacheService.Get(key);

            }

            var postList = _postRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active && p.Recommend, false).ToList();
            _cacheService.Set(key, postList, SettingsManager.Blog.CacheDuration);


            return postList;
        }
        public IEnumerable<Post> LatesterPosts(int count)
        {
            var key = $"{EntityNames.Post}s_Latester_{count}";

            if (!SettingsManager.Blog.EnableCaching)
            {
                return _postRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Post>)_cacheService.Get(key);

            }

            var postList = _postRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active, false).ToList();
            _cacheService.Set(key, postList, SettingsManager.Blog.CacheDuration);


            return postList;
        }
        public IEnumerable<Post> LatesterPosts(int count, int categoryId)
        {
            if (categoryId == 0)
                return LatesterPosts(count);

            var key = $"{EntityNames.Post}s_Latester_{count}_{categoryId}";
            if (!SettingsManager.Blog.EnableCaching)
            {
                return _postRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active & p.CategoryId == categoryId, false).ToList();
            }

            if (_cacheService.IsSet(key))
            {
                return (List<Post>)_cacheService.Get(key);

            }

            var postList = _postRepository.GetPagedElements(0, count, p => p.CreatedDate, p => p.Active & p.CategoryId == categoryId, false).ToList();
            _cacheService.Set(key, postList, SettingsManager.Blog.CacheDuration);


            return postList;
        }


    }
}
